package com.project.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.project.bean.UserBean;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class JsonServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        List<UserBean> list = new ArrayList<>();
        list.add(new UserBean(1,"张三","111","13920393283"));
        list.add(new UserBean(3,"李四","333","18930293825"));
        list.add(new UserBean(8,"王五","444","15839403940"));

        ObjectMapper om = new ObjectMapper();
        //将list集合转化为json字符串
        String jsonStr = om.writeValueAsString(list);
        resp.getWriter().print(jsonStr);
    }
}
